<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Traits\UserPrivilege;
use Bouncer;
use App\Models\SyUser as User;
use DB;
use App\Http\Requests\UserRequest;

class UserController extends Controller {

    use UserPrivilege;


    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request) {
        $perPage = $request->input('pageSize', 15);
        $name = $request->input('name', '');
        $query = User::query();
        $company = $request->input('company');
        $site = $request->input('site');
        
        $query->company($company)->site($site);
        
        if (!empty($name)) {
            $query->where('username', 'like', $name . '%');
        }
        $created = $request->input('created_at', []);
        if (!empty($created)) {
            $query->whereBetween('created_at', $created);
        }

        $query->auth();

        Bouncer::scope()->to(null);
        
        $users = $query->with(['company' => function($q) {
                        $q->select(['Co_Name', 'Co_ID']);
                    }, 'userinfo' => function($q) {
                        $q->select(['userphone', 'userid']);
                    }, 'roles' => function($q) {
                        $q->select(['id', 'name', 'title']);
                    },
                    'area' => function($q) {
                        $q->select(['AreaId', 'AreaName', 'area_text']);
                    }
                            ])->paginate($perPage);

        return $this->success('', ['data' => $users]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(UserRequest $request) {
		
        $data = $request->input();
     
        $user = User::create($data);

        if ($user) {
            Bouncer::assign(config('auth.roles.default'))->to($user);
            Bouncer::sync($user)->roles($request->input('role', []));
            return $this->success('添加成功');
        } else {
            return $this->error('添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(UserRequest $request, $id) {
        $user = User::findOrFail($id);

        $data = $request->input();
		$user->fill($data);
        $ret = $user->save();

        if ($ret) {
            Bouncer::sync($user)->roles($request->input('role', []));
            return $this->success('保存成功');
        } else {
            return $this->error('保存失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        $authUser = auth()->user();
        if($authUser->userid==$id) {
            return $this->error('禁止删除自己');
        }
        $user = User::findOrFail($id);
        if($user->isSuper()) {
            return $this->error('禁止删除');
        }
        if (!$user->delete()) {
            return $this->error('删除失败');
        }
    }

    public function getRoles($id) {
        if(!$id) {
             $user = $this->user();
        }else{
            $user = User::find($id);
        }
       //Bouncer::scope()->to($user->userid);
	   Bouncer::scope()->to($user->Co_ID);
	   
        Bouncer::scope()->onlyRelations();
  
        $currentRoles = $user->roles()->get();
       
        $allRoles = Bouncer::role()
                ->select(['name as value', 'title as label'])
                ->when(!$this->user()->isSuper(), function($query){
                    $query->whereNotIn('name', [config('auth.roles.super'), config('auth.roles.admin')]);
                })
                ->get();
        $myRoles = $currentRoles->pluck('name');
        return compact('allRoles', 'myRoles');
    }

    public function updateRoles(Request $request) {
        $uid = $request->input('id');
        $user = User::findOrFail($uid);
        Bouncer::sync($user)->roles($request->input('roles', []));
        return $this->success('更新用户角色成功');
    }

}
